// JavaScript Document applyPolicySiteFilterAction
///Custom PlaceHodler Name Not Unique
$(document).ready(function() {
  $("#edit-policy-add-new").click(function(){
    addNewPolicyDialog(700, 510, 'Create New Policy');
    return false;
  });
  
  $("#edit-manage-template-type").click(function(){
    window.location = baseurl + 'templatetype';
  });

  $("#edit-template-add-new").click(function(){
      addNewTemplateTypeDialog(600, 210, 'Create New Template Type');
      return false;
  });
  $("#edit-placeholder-add-new").click(function(){
      addNewPlaceholderDialog(600, 210, 'Create New Placeholder');
      return false;
  })

  $('#edit-policy-search-date').datepicker({
    dateFormat:'mm-dd-yy'
  });

  $('#edit-template-search-date').datepicker({
    dateFormat:'mm-dd-yy'
  });
  $('#edit-placeholder-search-date').datepicker({
    dateFormat:'mm-dd-yy'
  });
  $("#srt_insertedDate").addClass("sortDsc");
  $("#edit-more-actions").click(function(){
    moreactions();
    return false;
  });

  $("#edit-templatetype-group-activate").click(function() {
    var checkbox_values = [];
    $('input[@name=checkBoxList]:checked').each(function(i){
      checkbox_values[i] = $(this).val(); //store the selected values in an array
    });
    if(checkbox_values.length == 0){
      openAlertDialog(400, 150, 'Information', 'Please select atleast one template type to activate', 'information');
      return false;
    }
    var n =0;
    for(i=0;i<checkbox_values.length;i++){
      var templatetypeActive;
      templatetypeActive = $('#template_type_status_'+checkbox_values[i]).html();
      n = templatetypeActive.search('Active');
      if(n >= 0 ){
        openAlertDialog(400, 150, 'Information', 'Please select the template type which is in Inactive status', 'information');
        return false;
      }
    }
    activateDeactivateItems(checkbox_values, 'Active');
    return false;
  });
  $("#edit-templatetype-group-deactivate").click(function() {
    var checkbox_values = [];
    $('input[@name=checkBoxList]:checked').each(function(i){
      checkbox_values[i] = $(this).val(); //store the selected values in an array
    });
    if(checkbox_values.length == 0){
      openAlertDialog(400, 150, 'Information', 'Please select atleast one template type to deactivate', 'information');
      return false;
    }
    var n =0;
    for(i=0;i<checkbox_values.length;i++){
      var templatetypeInactive;
      templatetypeInactive = $('#template_type_status_'+checkbox_values[i]).html();
      n = templatetypeInactive.search('Inactive');
      if(n >= 0 ){
        openAlertDialog(400, 150, 'Information', 'Please select the template type which is in Inactive status', 'information');
        return false;
      }
    }
    activateDeactivateItems(checkbox_values, 'Inactive');
    return false;
  });

});

function activateDeactivateItems(checkbox_values, status){
  var title;
  var msg_str;
  var question;
  var action;
  if(status=='Active'){
    title       = 'Activated';
    msg_str     = 'activated';
    question    = 'activate';
    action      = 'Activate';
  }else{
    title       = 'Deactivated';
    msg_str     = 'deactivated';
    question    = 'deactivate';
    action      = 'Deactivate';
  }
  $('#dialog').html('<div style="padding-top:50px; padding-left:260px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  openConfirmBox(function(){
    $('#dialog').html('<div style="padding-top:50px; padding-left:260px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
    $.ajax({
      type: "POST",
      url : baseurl+'templatetype/groupaction',
      data: '&template_ids=' + checkbox_values + '&status=' + status,
      success: function(res){
        $('#alertdialog').dialog('destroy');
        eval("var json="+res);
        if(json.Message == 'Success'){
          var pageno   = $('#hid_pageno').val();
          applyTemplatetypeFilterAction(pageno);
          openAlertDialog(400, 150, title, 'Selected template types '+msg_str+' successfully','success');
          $('input[name=checkAll]').attr('checked', false);
          return false;
        }
        else{
          openAlertDialog(400, 150, 'Error', 'Error in updating the template types');
          return false;
        }
      },
      error : function (res) {
        handleRequestError(res);
      }
    });
  },300,120,"Confirm "+action,(question=="deactivate"?"Template type will be deactivated. Are you sure?":"Do you want to "+question+"?"));
  return false;
}

/**
 * Function to sort
 * @param sortField string
 * @param module string val: Templatetype, Policy, Placeholder
 */
function sortListColumn(module, sortField){
  $("#listingResultset").html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
  var limit = 10;
  var hid_sort = $('#hid_sort').val();
  var orig_sort = sortField;
  var pageno = parseInt($('#hid_pageno').val());
  var urls = "";
  var data = eval("filterdata_"+module+"();");
  if(hid_sort){
    hid_sort = hid_sort.split(",");
    if(hid_sort[1] == sortField ){
      if(hid_sort[0]=="ascending")
        sortField = ["descending", sortField];
      else
        sortField = ["ascending", sortField];
    }else{
      sortField = ["ascending", sortField];
      $('#srt_'+hid_sort[1]).attr('class','sortNone');
    }
  }else{
    sortField = ["ascending", sortField];
  }

  urls = module.toLowerCase() + "/filter";

  $.ajax({
    type : "POST",
    url : baseurl+urls,
    data: "limit="+limit+"&page="+pageno+"&sort_condition="+sortField+data,
    async : false,
    cache : false,
    success : function (msg) {
      $("#listingResultset").html(msg);
      $('#srt_'+orig_sort).attr('class', sortField[0]=="ascending"?"sortAsc":"sortDsc");
      $('#hid_sort').val(sortField);
      refresh_list_pagination(module, pageno);
      $('#checkAll').attr('checked', false);
    }
  });
  return false;
}

function filterdata_Policy(){
  //prepare the field values for filtering
  var policy_name           = $.trim($("#edit-policy-search-name").val());
  var policy_status         = $("#edit-policy-search-status").val();
  var policy_type           = $("#edit-policy-search-type").val();
  var policy_approved_by    = $("#edit-policy-search-approver").val();
  var policy_approval_date  = $("#edit-policy-search-date").val();

  var data = "";
  if($.trim(policy_name)!=""){
    data+="&policy_name="+encodeURIComponent(policy_name);
  }
  if($.trim(policy_status)!=""){
    data+="&policy_status="+policy_status;
  }
  if($.trim(policy_type)!=""){
    data+="&policy_type="+policy_type;
  }
  if($.trim(policy_approved_by)!=""){
    data+="&policy_approved_by="+encodeURIComponent(policy_approved_by);
  }
  if($.trim(policy_approval_date)!=""){
    data+="&policy_approval_date="+policy_approval_date;
  }
  return data;
}

function filterdata_PolicySite(){
  //prepare the field values for filtering
  var policy_name           = $.trim($("#edit-policy-search-name").val());
  var policy_type           = $("#edit-policy-search-type").val();
  var policy_approved_by    = $("#edit-policy-search-approver").val();
  var policy_approval_date  = $("#edit-policy-search-date").val();

  var data = "";
  if($.trim(policy_name)!=""){
    data+="&policy_name="+policy_name;
  }
  if($.trim(policy_type)!=""){
    data+="&policy_type="+policy_type;
  }
  if($.trim(policy_approved_by)!=""){
    data+="&policy_approved_by="+policy_approved_by;
  }
  if($.trim(policy_approval_date)!=""){
    data+="&policy_approval_date="+policy_approval_date;
  }
  return data;
}

function filterdata_Templatetype(){
  var template_name             = $.trim($("#edit-template-search-name").val());
  var template_status           = $("#edit-template-search-status").val();
  var template_approval_date    = $("#edit-template-search-date").val();
  var data = "";
  if($.trim(template_name)!=""){
    data+="&template_name="+template_name;
  }
  if($.trim(template_status)!=""){
    data+="&template_status="+template_status;
  }
  if($.trim(template_approval_date)!=""){
    data+="&template_approval_date="+template_approval_date;
  }
  return data;
}

function filterdata_Placeholder(){
  var placeholder_name             = $.trim($("#edit-placeholder-search-name").val());
  var placeholder_status           = $("#edit-placeholder-search-status").val();
  var placeholder_approval_date    = $("#edit-placeholder-search-date").val();
  var data = "";
  if($.trim(placeholder_name)!=""){
    data+="&placeholder_name="+placeholder_name;
  }
  if($.trim(placeholder_status)!=""){
    data+="&placeholder_status="+placeholder_status;
  }
  if($.trim(placeholder_approval_date)!=""){
    data+="&placeholder_approval_date="+placeholder_approval_date;
  }
  return data;
}

function filterdata_PlaceholderSite(){
  var placeholder_name             = $.trim($("#edit-placeholder-search-name").val());
  var placeholder_status           = $("#edit-placeholder-search-status").val();
  var placeholder_approval_date    = $("#edit-placeholder-search-date").val();
  var data = "";
  if($.trim(placeholder_name)!=""){
    data+="&placeholder_name="+placeholder_name;
  }
  if($.trim(placeholder_status)!=""){
    data+="&placeholder_status="+placeholder_status;
  }
  if($.trim(placeholder_approval_date)!=""){
    data+="&placeholder_approval_date="+placeholder_approval_date;
  }
  return data;
}

function filterdata_Defaultplaceholder(){
  var placeholder_name             = $.trim($("#edit-placeholder-search-name").val());
  var data = "";
  if($.trim(placeholder_name)!=""){
    data+="&placeholder_name="+placeholder_name;
  }
  return data;
}

function refresh_list_pagination(module, pageno){
  var limit = $('#hid_limit').val();
  var page = parseInt(pageno);
  var counter = $('#hid_totalRec').val();

  if(counter>0){
    var str="";
    var to = page*limit;
    str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
      if (page > 1) {
        str += '<b><a href="javascript:void(0)" onclick = "apply'+module+'FilterAction('+(page-1)+')" class="red"><< Previous</a></b>';
      }

      if (to < counter) {
        str += ' <span class="red"> |</span><b><a href="javascript:void(0)" onclick = "apply'+module+'FilterAction('+(page+1)+')" class="red">Next >></a></b>';
      }

    $("#pagingdivtop").html(str);
    $("#pagingdivbottom").html(str);
    $('#checkAll').attr('checked', false);
  }else{
    $("#pagingdivtop").html("");
    $("#pagingdivbottom").html("");
  }
}

//function to close the dialog box
function closeDialog(){
  $('#dialog').dialog('destroy');
  return false;
}

//function to apply filter option
function applyPolicyFilterAction(pageno){
  //prepare the field values for filtering
  var policy_name           = $.trim($("#edit-policy-search-name").val());
  var policy_status         = $.trim($("#edit-policy-search-status").val());
  var policy_type           = $.trim($("#edit-policy-search-type").val());
  var policy_approved_by    = $("#edit-policy-search-approver").val();
  var policy_approval_date  = $("#edit-policy-search-date").val();
  var sortval               = $('#hid_sort').val();

  $('#listingResultset').html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
  $("#pagingdivtop").hide();
  $("#pagingdivbottom").hide();

  $.ajax({
    type : "POST",
    url : baseurl + "policy/filter",
    data : "policy_name="+encodeURIComponent(policy_name)+"&policy_status="+encodeURIComponent(policy_status)+"&policy_type="+encodeURIComponent(policy_type)+"&policy_approved_by="+encodeURIComponent(policy_approved_by)+"&policy_approval_date="+policy_approval_date+(pageno>1?'&page='+pageno:'')+(sortval!=""?'&sort_condition='+sortval:''),
    //data : (pageno>1?'&page='+pageno:'')+(sortval!=""?'&sort_condition='+sortval:''),
    async : false,
    cache : false,
    success : function (msg) {
      $("#listingResultset").html(msg);
      var limit = $('#hid_limit').val();
      var page = parseInt(pageno);
      var counter = $("#hid_totalRec").val();

      if(counter>0){
        var str="";
        var to = page*limit;
        str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
        if (page > 1) {
          str += '<a href="javascript:void(0)" onclick = "applyPolicyFilterAction('+(page-1)+')" class="red"><< Previous</a>';
        }

        if (to < counter) {
          str += ' <span class="red">|</span> <a href="javascript:void(0)" onclick = "applyPolicyFilterAction('+(page+1)+')" class="red">Next >></a>';
        }

        $("#pagingdivtop").html(str);
        $("#pagingdivbottom").html(str);
        $("#pagingdivtop").show();
        $("#pagingdivbottom").show();
        $('#checkAll').attr('checked', false);
      }
    }
  });
  $("#hid_pageno").val(pageno);
  return false;
}
//function to apply filter option
function applyPolicySiteFilterAction(pageno){
  //prepare the field values for filtering
  var policy_name           = $.trim($("#edit-policy-search-name").val());
  var policy_status         = $.trim($("#edit-policy-search-status").val());
  var policy_type           = $.trim($("#edit-policy-search-type").val());
  var policy_approved_by    = $("#edit-policy-search-approver").val();
  var policy_approval_date  = $("#edit-policy-search-date").val();
  var sortval               = $('#hid_sort').val();

  $('#listingResultset').html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
  $("#pagingdivtop").hide();
  $("#pagingdivbottom").hide();

  $.ajax({
    type : "POST",
    url : baseurl + "policysite/filter",
    data : "policy_name="+encodeURIComponent(policy_name)+"&policy_status="+encodeURIComponent(policy_status)+"&policy_type="+encodeURIComponent(policy_type)+"&policy_approved_by="+encodeURIComponent(policy_approved_by)+"&policy_approval_date="+policy_approval_date+(pageno>1?'&page='+pageno:'')+(sortval!=""?'&sort_condition='+sortval:''),
    //data : (pageno>1?'&page='+pageno:'')+(sortval!=""?'&sort_condition='+sortval:''),
    async : false,
    cache : false,
    success : function (msg) {
      $("#listingResultset").html(msg);
      var limit = $('#hid_limit').val();
      var page = parseInt(pageno);
      var counter = $("#hid_totalRec").val();

      if(counter>0){
        var str="";
        var to = page*limit;
        str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
        if (page > 1) {
          str += '<a href="javascript:void(0)" onclick = "applyPolicySiteFilterAction('+(page-1)+')" class="red"><< Previous</a>';
        }

        if (to < counter) {
          str += ' <span class="red">|</span> <a href="javascript:void(0)" onclick = "applyPolicySiteFilterAction('+(page+1)+')" class="red">Next >></a>';
        }

        $("#pagingdivtop").html(str);
        $("#pagingdivbottom").html(str);
        $("#pagingdivtop").show();
        $("#pagingdivbottom").show();
        $('#checkAll').attr('checked', false);
      }
    }
  });
  $("#hid_pageno").val(pageno);
  return false;
}

//function to apply filter option
function applyTemplatetypeFilterAction(pageno){
  var template_name             = $.trim($("#edit-template-search-name").val());
  var template_status           = $("#edit-template-search-status").val();
  var template_approval_date    = $("#edit-template-search-date").val();
  var sortval   = $('#hid_sort').val();

  $('#listingResultset').html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
  $("#pagingdivtop").hide();
  $("#pagingdivbottom").hide();

  $.ajax({
    type : "POST",
    url : baseurl+"templatetype/filter",
    data : (sortval!=""?'&sort_condition='+sortval:'')+(pageno>1?'&page='+pageno:'')+'&template_name='+template_name+'&template_status='+template_status+'&template_approval_date='+template_approval_date,
    async : false,
    cache : false,
    success : function (msg) {
      $("#listingResultset").html(msg);
      var limit = $('#hid_limit').val();
      var page = parseInt(pageno);
      var counter = $("#hid_totalRec").val();

      if(counter>0){
        var str="";
        var to = page*limit;
        str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
        if (page > 1) {
          str += '<a href="javascript:void(0)" onclick = "applyTemplatetypeFilterAction('+(page-1)+')" class="red"><< Previous</a>';
        }

        if (to < counter) {
          str += ' <span class="red">|</span> <a href="javascript:void(0)" onclick = "applyTemplatetypeFilterAction('+(page+1)+')" class="red">Next >></a>';
        }

        $("#pagingdivtop").html(str);
        $("#pagingdivbottom").html(str);
        $("#pagingdivtop").show();
        $("#pagingdivbottom").show();
        $('#checkAll').attr('checked', false);
      }
    }
  });
  $("#hid_pageno").val(pageno);
  return false;
}

//function to apply filter option
function applyPlaceholderFilterAction(pageno){
  var placeholder_name             = $.trim($("#edit-placeholder-search-name").val());
  var placeholder_status           = $("#edit-placeholder-search-status").val();
  var placeholder_approval_date    = $("#edit-placeholder-search-date").val();
  var sortval   = $('#hid_sort').val();

  $('#listingResultset').html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
  $("#pagingdivtop").hide();
  $("#pagingdivbottom").hide();

  $.ajax({
    type : "POST",
    url : baseurl+"placeholder/filter",
    data : (sortval!=""?'&sort_condition='+sortval:'')+(pageno>1?'&page='+pageno:'')+'&placeholder_name='+placeholder_name+'&placeholder_status='+placeholder_status+'&placeholder_approval_date='+placeholder_approval_date,
    async : false,
    cache : false,
    success : function (msg) {
      $("#listingResultset").html(msg);
      var limit = $('#hid_limit').val();
      var page = parseInt(pageno);
      var counter = $("#hid_totalRec").val();

      if(counter>0){
        var str="";
        var to = page*limit;
        str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
        if (page > 1) {
          str += '<a href="javascript:void(0)" onclick = "applyPlaceholderFilterAction('+(page-1)+')" class="red"><< Previous</a>';
        }

        if (to < counter) {
          str += ' <span class="red">|</span> <a href="javascript:void(0)" onclick = "applyPlaceholderFilterAction('+(page+1)+')" class="red">Next >></a>';
        }

        $("#pagingdivtop").html(str);
        $("#pagingdivbottom").html(str);
        $("#pagingdivtop").show();
        $("#pagingdivbottom").show();
        $('#checkAll').attr('checked', false);
      }
    }
  });
  $("#hid_pageno").val(pageno);
  return false;
}

//function to apply filter option
function applySitePlaceholderFilterAction(pageno){
  var placeholder_name             = $.trim($("#edit-placeholder-search-name").val());
  var placeholder_status           = $("#edit-placeholder-search-status").val();
  var placeholder_approval_date    = $("#edit-placeholder-search-date").val();
  var sortval   = $('#hid_sort').val();

  $('#listingResultset').html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
  $("#pagingdivtop").hide();
  $("#pagingdivbottom").hide();

  $.ajax({
    type : "POST",
    url : baseurl+"placeholdersite/filter",
    data : (sortval!=""?'&sort_condition='+sortval:'')+(pageno>1?'&page='+pageno:'')+'&placeholder_name='+placeholder_name+'&placeholder_status='+placeholder_status+'&placeholder_approval_date='+placeholder_approval_date,
    async : false,
    cache : false,
    success : function (msg) {
      $("#listingResultset").html(msg);
      var limit = $('#hid_limit').val();
      var page = parseInt(pageno);
      var counter = $("#hid_totalRec").val();

      if(counter>0){
        var str="";
        var to = page*limit;
        str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
        if (page > 1) {
          str += '<a href="javascript:void(0)" onclick = "applyPlaceholderFilterAction('+(page-1)+')" class="red"><< Previous</a>';
        }

        if (to < counter) {
          str += ' <span class="red">|</span> <a href="javascript:void(0)" onclick = "applyPlaceholderFilterAction('+(page+1)+')" class="red">Next >></a>';
        }

        $("#pagingdivtop").html(str);
        $("#pagingdivbottom").html(str);
        $("#pagingdivtop").show();
        $("#pagingdivbottom").show();
        $('#checkAll').attr('checked', false);
      }
    }
  });
  $("#hid_pageno").val(pageno);
  return false;
}

//function to open dialog box for adding new policies
function addNewPolicyDialog (width, height, title, legalEntityId) {
  var wid       = width;
  var heit      = height;
  var buttons   = false;
  
  $('#dialog').dialog({
    autoOpen    : false,
    width       : wid,
    height      : heit,
    bgiframe    : true,
    resizable   : false,
    title       : title,
    modal       : true,
    show        : 'puff',
    close       : function () {
      $('#dialog').dialog('destroy');
    }
  });
  $('#dialog').dialog('open');
  var h         = heit;
  if(buttons){
    h           = heit-95;
  }else{
    h           = heit-35;
  }
  $('#dialog').css({
    'overflow-y': 'auto',
    'width'     : (wid-18)+'px',
    'height'    : h + 'px'
  }).show();

  $('#dialog').html('<div style="padding-top:200px; padding-left:310px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  addPolicy(legalEntityId);
}

//Function to display add policy form
function addPolicy(legalEntityId) {
  policycontent_create = Array();
  title_content = '';
  $.ajax({
    type  : "GET",
    url   : baseurl + 'policy/add/' + legalEntityId,
    async : true,
    cache : false,
    success : function (res) {
        $('#dialog').html(res);
        $('#edit-policy-content').css("width", "318px");
      	$("#edit-publish").focus();
        fckeditor('edit-policy-content');
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function editorAddText(text){
    ckeditor.insertText(text);
}

function insertPlaceholderInEditor(){
    var textToInsert = '[' + $("#edit-policy-placeholders").val() + ']';
    ckeditor.insertText(textToInsert);
}

//Function to save the data for policy
function submitPolicy(type) {
  var policy_name       = $.trim($("#edit-policy-name").val());
  var policy_type       = $("#edit-policy-type").val();
  var policy_content    = ckeditor.getData();
  var msg_str           = '';
  var strRegExp         = "^[A-Za-z0-9\\s-_]{1,255}$";

  if (policy_name == "") {
    msg_str = msg_str + "Please enter the policy name. <br />";
  }else if(TestRegExp(policy_name, strRegExp) == false){
    msg_str = msg_str + "Please enter valid policy name. Only A-Z a-Z 0-9 - _ and spaces are allowed.<br />";
  }
  if (policy_type == "") {
    msg_str = msg_str + "Please select template type. <br />";
  }
  if (policy_content == "" || policy_content == "<br />\n" || policy_content == "\n") {
    msg_str = msg_str + "Please enter the policy content. <br />";
  }
  if(msg_str != ''){
    styleStatusMessages(msg_str, "statusMessage", "failure");
    return false;
  }
  $('#dialog').html('<div style="padding-top:200px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type    : "POST",
    url     : baseurl + 'policy/add_action',
    data    : '&policy_name='+encodeURIComponent(policy_name)+'&policy_type='+encodeURIComponent(policy_type) + '&policy_content=' + encodeURIComponent(policy_content) + '&policy_action=' + encodeURIComponent(type),
    success: function(msg){
      eval("var json="+msg);
      if(json.Message=="Success"){
        $('#dialog').dialog('destroy');
        applyPolicyFilterAction(1);
        openAlertDialog(350, 130, 'Information', json.Error, "success");
      }else{
          if(json.Message=="Failure"){
            if ((json.Error).search("Content Template Name Not Unique") >= 0) {
              var err_msg = "Content Template already exists";
            }
            else {
              var err_msg = json.Error;
            }
            $.ajax({
              type    : "GET",
              url     : baseurl + 'policy/add',
              cache   : false,
              success : function (res) {
                $('#dialog').html(res);
                $('#edit-policy-name').val(policy_name);
                $('#edit-policy-type').val(policy_type);
                $('#edit-policy-content').val(policy_content);
                fckeditor('edit-policy-content');
                styleStatusMessages(err_msg, "statusMessage", "failure");
              },
              error   : function (res) {
                handleRequestError(res);
              }
            });
            resize_dialog(700, 510);
          }
          else{
            openAlertDialog(300, 130, 'Error', 'Error in publishing the policy');
          }
        }
      }
  });
  return false;
}

var policycontent_create = new Array();
var title_content = '';
function previewPolicy(id){
  title_content = $("#ui-dialog-title-dialog").html();
  $("#ui-dialog-title-dialog").html("Preview Policy Content");
  var policy_name       = $.trim($("#edit-policy-name").val());
  var policy_type       = $("#edit-policy-type").val();
  var policy_content    = ckeditor.getData().replace(/&/gi, '__and__');
  var msg_str           = '';
  var strRegExp         = "^[A-Za-z0-9\\s-_]{1,255}$";

  if (policy_name == "") {
    msg_str = msg_str + "Please enter the policy name. <br />";
  }else if(TestRegExp(policy_name, strRegExp) == false){
    msg_str = msg_str + "Please enter valid policy name. Only A-Z a-Z 0-9 - _ and spaces are allowed.<br />";
  }
  if (policy_type == "") {
    msg_str = msg_str + "Please select template type. <br />";
  }
  if (policy_content == "" || policy_content == "<br />\n" || policy_content == "\n") {
    msg_str = msg_str + "Please enter the policy content. <br />";
  }
  if(msg_str != ''){
    styleStatusMessages(msg_str, "statusMessage", "failure");
    return false;
  }

  var createpolicy_info = {};
	//Store the sequence values to the temporary sequence array
	createpolicy_info['policy_name'] = policy_name;
	createpolicy_info['policy_content'] = policy_content;
	createpolicy_info['policy_type'] = policy_type;
	policycontent_create.push(createpolicy_info);

  $('#dialog').html('<div style="padding-top:200px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type  : "POST",
    url   : baseurl + 'policy/preview',
    data  : 'policy_name='+encodeURIComponent(policy_name)+'&policy_type='+encodeURIComponent(policy_type) + '&policy_content=' + encodeURIComponent(policy_content) + "&tempId=" + id,
    async : true,
    cache : false,
    success : function (res) {
      $("#dialog").html(res);
    },
    error : function (res) {
      handleRequestError(res);
      return false;
    }
  });
  return false;
}

//Function to create backToCreatePolicy
function backToCreatePolicy (tempId) {
  $('#dialog').html('<div style="padding-top:200px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  if (tempId != "" && typeof tempId != "undefined") {
    $("#ui-dialog-title-dialog").html(title_content);
    urls = baseurl + 'policy/edit/' + tempId;
  }
  else {
    $("#ui-dialog-title-dialog").html(title_content);
    urls = baseurl + 'policy/add/';
  }

  $.ajax({
  type  : "POST",
  data  : "PolicyContent=" + JSON.stringify(policycontent_create),
  url   : urls,
  async : true,
  cache : false,
  success : function (res) {
    policycontent_create = Array();
    title_content = '';
    $('#dialog').html(res);
    $('#edit-policy-content').css("width", "318px");
    fckeditor('edit-policy-content');
    $("#edit-policy-name").focus();
  },
  error : function (res) {
    handleRequestError(res);
  }
});
}

function editPreviewPolicy(policyId){
  var policy_name       = $.trim($("#edit-policy-name").val());
  var policy_type       = $("#edit-policy-type").val();
  var policy_content    = ckeditor.getData();
  var placeholder_vals  = $('#edit-policy-placeholders-values').val();
  var contentPreview    = $('#dialog').html();
  $.ajax({
    type  : "POST",
    url   : baseurl + 'policy/edit_preview',
    data  : '&policy_id='+policyId+'&policy_name='+encodeURIComponent(policy_name)+'&policy_type='+encodeURIComponent(policy_type)+'&policy_content='+encodeURIComponent(policy_content)+'&placeholder_vals='+encodeURIComponent(placeholder_vals),
    async : true,
    cache : false,
    success : function (res) {
        applyPolicyFilterAction(1);
        eval("var json="+res);
        if(json.Message=='Success'){
            reopen_dialog(700,510,policy_name);
            $('#dialog').html(json.Content);
        }else if(json.Message=='Failure'){
            $('#dialog').html(contentPreview);
        }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}


function openViewDetailDialog(id, width, height, title){
  var wid       = width;
  var heit      = height;
  var buttons   = false;

  $('#dialog').dialog({
    autoOpen    : false,
    width       : wid,
    height      : heit,
    bgiframe    : true,
    resizable   : false,
    title       : title,
    modal       : true,
    show        : 'puff',
    close       : function () {
      $('#dialog').dialog('destroy');
    }
  });
  $('#dialog').dialog('open');
  var h         = heit;
  if(buttons){
    h           = heit-95;
  }else{
    h           = heit-35;
  }
  $('#dialog').css({
    'overflow-y': 'auto',
    'width'     : (wid-18)+'px',
    'height'    : h + 'px'
  }).show();

  $('#dialog').html('<div style="padding-top:110px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  viewPolicyDetail(id);
}

function viewPolicyDetail(id){
  $.ajax({
    type  : "GET",
    url   : baseurl + '?q=policy/detail/' + id,
    async : true,
    cache : false,
    success : function (res) {
        $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
  return false;
}

function openViewSitePolicyDetailDialog(id, width, height, title){
  var wid       = width;
  var heit      = height;
  var buttons   = false;

  $('#dialog').dialog({
    autoOpen    : false,
    width       : wid,
    height      : heit,
    bgiframe    : true,
    resizable   : false,
    title       : title,
    modal       : true,
    show        : 'puff',
    close       : function () {
      $('#dialog').dialog('destroy');
    }
  });
  $('#dialog').dialog('open');
  var h         = heit;
  if(buttons){
    h           = heit-95;
  }else{
    h           = heit-35;
  }
  $('#dialog').css({
    'overflow-y': 'auto',
    'width'     : (wid-18)+'px',
    'height'    : h + 'px'
  }).show();

  $('#dialog').html('<div style="padding-top:110px; padding-left:280px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  viewSitePolicyDetail(id);
}

function viewSitePolicyDetail(id){
  $.ajax({
    type  : "GET",
    url   : baseurl + 'policysite/detail/' + id,
    async : true,
    cache : false,
    success : function (res) {
        $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
  return false;
}

function editPolicyDialog(id, width, height, title) {
  var wid       = width;
  var heit      = height;
  var buttons   = false;

  $('#dialog').dialog({
    autoOpen    : false,
    width       : wid,
    height      : heit,
    bgiframe    : true,
    resizable   : false,
    title       : title,
    modal       : true,
    show        : 'puff',
    close       : function () {
      $('#dialog').dialog('destroy');
    }
  });
  $('#dialog').dialog('open');
  var h         = heit;
  if(buttons){
    h           = heit-95;
  }else{
    h           = heit-35;
  }
  $('#dialog').css({
    'overflow-y': 'auto',
    'width'     : (wid-18)+'px',
    'height'    : h + 'px'
  }).show();

  editContentTemplate(id, title);
}

function editContentTemplate(id, title){
  policycontent_create = Array();
  title_content = '';
  reopen_dialog(700,510,"Edit " + title);
  $('#dialog').html('<div style="padding-top:175px; padding-left:310px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "GET",
    url : baseurl+'?q=policy/edit/'+id,
    async : true,
    cache : false,
    success : function (res) {
        $('#dialog').html(res);
        $("#edit-publish").focus();
        fckeditor('edit-policy-content');
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function editPolicyAction(policyId, action) {
  var policy_name       = $.trim($("#edit-policy-name").val());
  var policy_type       = $("#edit-policy-type").val();
  var policy_content    = ckeditor.getData();
  var strRegExp         = "^[A-Za-z0-9\\s-_]{1,255}$";
  var msg_str           = '';

  if (policy_name == "") {
    msg_str = msg_str + "Please enter the policy name. <br />";
  }else if(TestRegExp(policy_name, strRegExp) == false){
    msg_str = msg_str + "Please enter valid policy name. Only A-Z a-Z 0-9 - _ and spaces are allowed.<br />";
  }
  if (policy_type == "") {
    msg_str = msg_str + "Please select template type. <br />";
  }
  if (policy_content == "" || policy_content == "<br />\n" || policy_content == "\n") {
    msg_str = msg_str + "Please enter the policy content. <br />";
  }
  if(msg_str != ''){
    styleStatusMessages(msg_str, "statusMessage", "failure");
    return false;
  }
  $('#dialog').html('<div style="padding-top:200px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type    : "POST",
    url     : baseurl + '?q=policy/edit_action',
    data    : '&policy_id='+encodeURIComponent(policyId)+ '&policy_name='+encodeURIComponent(policy_name) + '&policy_type=' + policy_type + '&policy_content=' + encodeURIComponent(policy_content) + '&policy_action=' + encodeURIComponent(action),
    success: function(msg){
      eval("var json="+msg);
      if(json.Message=="Success"){
        $('#dialog').dialog('destroy');
        var pageno = parseInt($('#hid_pageno').val());
        applyPolicyFilterAction(pageno);
        openAlertDialog(350, 130, 'Information', json.Error, "success");
      }else{
        if(json.Message=='Failure'){
          if ((json.Error).search("Content Template Name Not Unique") >= 0) {
            var err_msg = "Content Template already exists";
          }
          else {
            var err_msg = json.Error;
          }
          $.ajax({
            type : "GET",
            url : baseurl+'policy/edit/'+policyId,
            async : true,
            cache : false,
            success : function (res) {
                $('#dialog').html(res);
                $("#edit-policy-name").val(policy_name);
                $("#edit-policy-type").val(policy_type);
                $("#edit-policy-content").val(policy_content);
                fckeditor('edit-policy-content');
                resize_dialog(700, 510);
                styleStatusMessages(err_msg, "statusMessage", "failure");
            },
            error : function (res) {
              handleRequestError(res);
            }
          });
        }
      }
    }
  });
  return false;
}
//function to open dialog box for adding new template types
function templateTypeDialog (width, height, title) {
  var wid       = width;
  var heit      = height;
  var buttons   = false;

  $('#dialog').dialog({
    autoOpen    : false,
    width       : wid,
    height      : heit,
    bgiframe    : true,
    resizable   : false,
    title       : title,
    modal       : true,
    show        : 'puff',
    close       : function () {
      $('#dialog').dialog('destroy');
    }
  });
  $('#dialog').dialog('open');
  var h         = heit;
  if(buttons){
    h           = heit-95;
  }else{
    h           = heit-35;
  }
  $('#dialog').css({
    'overflow-y': 'auto',
    'width'     : (wid-18)+'px',
    'height'    : h + 'px'
  }).show();

  $('#dialog').html('<div style="padding-top:50px; padding-left:260px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  templateTypeList();
}

//Function to display Template type list
function templateTypeList() {
  $.ajax({
    type  : "GET",
    url   : baseurl + 'templatetype',
    async : true,
    cache : false,
    success : function (res) {
        $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
  return false;
}

//function to open dialog box for adding new template types
function addNewTemplateTypeDialog (width, height, title) {
  var wid       = width;
  var heit      = height;
  var buttons   = false;

  $('#dialog').dialog({
    autoOpen    : false,
    width       : wid,
    height      : heit,
    bgiframe    : true,
    resizable   : false,
    title       : title,
    modal       : true,
    show        : 'puff',
    close       : function () {
      $('#dialog').dialog('destroy');
    }
  });
  $('#dialog').dialog('open');
  var h         = heit;
  if(buttons){
    h           = heit-95;
  }else{
    h           = heit-35;
  }
  $('#dialog').css({
    'overflow-y': 'auto',
    'width'     : (wid-18)+'px',
    'height'    : h + 'px'
  }).show();

  $('#dialog').html('<div style="padding-top:50px; padding-left:260px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  addNewTemplateType();
}

//Function to display Template type list
function addNewTemplateType() {
  $.ajax({
    type  : "GET",
    url   : baseurl + '?q=templatetype/add',
    async : true,
    cache : false,
    success : function (res) {
        $('#dialog').html(res);
        $("#edit-templates-name").focus();
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
  return false;
}

//Function to save the data for policy
function submitTemplateType() {
  var templatetype_name     = $.trim($("#edit-templates-name").val());
  var templatetype_status   = $.trim($("#edit-templates-status").val());
  var message_str           = '';
  var height                = 0;
  var strRegExp             = "^[A-Za-z0-9\\s-_]{1,255}$";

  if (templatetype_name == "") {
    message_str = message_str + "Please enter the template type. <br />";
    height      = height + 20;
  }else if(TestRegExp(templatetype_name, strRegExp) == false){
    message_str = message_str + "Please enter valid template type. Only A-Z a-Z 0-9 - _ and spaces are allowed.<br />";
    height      = height + 20;
  }
  if (templatetype_status == "") {
    message_str = message_str + "Please select the status. <br />";
    height      = height + 20;
  }
  if(message_str != '') {
    resize_dialog(600, 190 + height);
    styleStatusMessages(message_str, "statusMessage", "failure");
    return false;
  }

  $('#dialog').html('<div style="padding-top:50px; padding-left:260px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type    : "POST",
    url     : baseurl + '?q=templatetype/add_action',
    data    : '&templatetype_name='+encodeURIComponent(templatetype_name)+ '&templatetype_status=' + templatetype_status,
    success: function(msg){
      eval("var json="+msg);
      if(json.Message=="Success"){
        $('#dialog').dialog('destroy');
        applyTemplatetypeFilterAction(1);
        openAlertDialog(350, 130, 'Information', 'Template type created successfully.', "success");
      }else{
          if(json.Message=="Failure"){
            if ((json.Error).search("Content Template Type Not Unique") >= 0) {
              var err_msg = "Template Type already exists";
            }
            else {
              var err_msg = json.Error;
            }
            $.ajax({
              type    : "GET",
              url     : baseurl + 'templatetype/add',
              cache   : false,
              success : function (res) {
                $('#dialog').html(res);
                $('#edit-templates-name').val(templatetype_name);
                $('#edit-templates-status').val(templatetype_status);
                styleStatusMessages(err_msg, "statusMessage", "failure");
              },
              error   : function (res) {
                handleRequestError(res);
              }
            });
            resize_dialog(600, 210);
          }
      }
    }
  });
  return false;
}

function openViewTemplateDetailDialog(id, width, height, title){
  var wid       = width;
  var heit      = height;
  var buttons   = false;

  $('#dialog').dialog({
    autoOpen    : false,
    width       : wid,
    height      : heit,
    bgiframe    : true,
    resizable   : false,
    title       : title,
    modal       : true,
    show        : 'puff',
    close       : function () {
      $('#dialog').dialog('destroy');
    }
  });
  $('#dialog').dialog('open');
  var h         = heit;
  if(buttons){
    h           = heit-95;
  }else{
    h           = heit-35;
  }
  $('#dialog').css({
    'overflow-y': 'auto',
    'width'     : (wid-18)+'px',
    'height'    : h + 'px'
  }).show();

  $('#dialog').html('<div style="padding-top:50px; padding-left:240px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  viewTemplateDetail(id);
}

function viewTemplateDetail(id){
  $.ajax({
    type  : "GET",
    url   : baseurl + 'templatetype/detail/' + id,
    async : true,
    cache : false,
    success : function (res) {
        $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
  return false;
}

//function to open dialog box for editing template types
function editTemplateDialog (id, width, height, title) {
$('#dialog').dialog('destroy');
  var wid       = width;
  var heit      = height;
  var buttons   = false;

  $('#dialog').dialog({
    autoOpen    : false,
    width       : wid,
    height      : heit,
    bgiframe    : true,
    resizable   : false,
    title       : 'Edit '+ title,
    modal       : true,
    show        : 'puff',
    close       : function () {
      $('#dialog').dialog('destroy');
    }
  });
  $('#dialog').dialog('open');
  var h         = heit;
  if(buttons){
    h           = heit-95;
  }else{
    h           = heit-35;
  }
  $('#dialog').css({
    'overflow-y': 'auto',
    'width'     : (wid-18)+'px',
    'height'    : h + 'px'
  }).show();

  editTemplateType(id, title);
}

function editTemplateType(id, title){
  //reopen_dialog(550, 180, "Edit " + title);
  $('#dialog').html('<div style="padding-top:30px; padding-left:240px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "GET",
    url : baseurl+'templatetype/edit/'+id,
    async : true,
    cache : false,
    success : function (res) {
        $('#dialog').html(res);
        $("#edit-templates-name").focus();
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function editTemplateAction(templateId) {
  var templatetype_name     = $.trim($("#edit-templates-name").val());
  var templatetype_status   = $.trim($("#edit-templates-status").val());
  var strRegExp             = "^[A-Za-z0-9\\s-_]{1,255}$";

  if (templatetype_name == "") {
    styleStatusMessages("Please enter the template type", "statusMessage", "failure");
    return false;
  }
  else if(TestRegExp(templatetype_name, strRegExp) == false){
    styleStatusMessages("Please enter valid template type. Only A-Z a-Z 0-9 - _ and spaces are allowed.<br />", "statusMessage", "failure");
    return false;
  }
  var content = $('#dialog').html();
  $('#dialog').html('<div style="padding-top:30px; padding-left:240px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type    : "POST",
    url     : baseurl + 'templatetype/edit_action',
    data    : '&templatetype_id='+encodeURIComponent(templateId)+ '&templatetype_name='+encodeURIComponent(templatetype_name)+ '&templatetype_status=' + templatetype_status,
    success: function(msg){
      eval("var json="+msg);
      if(json.Message=="Success"){
        $('#dialog').dialog('destroy');
        var pageno = parseInt($('#hid_pageno').val());
        applyTemplatetypeFilterAction(pageno);
        openAlertDialog(350, 130, 'Information', 'Template type updated successfully.', "success");
      }else{
        if(json.Message=="Failure"){
          if ((json.Error).search("Some service error occured") >= 0) {
            var err_msg = "Template Type already exists";
          }
          else {
            var err_msg = json.Error;
          }
          $('#dialog').html(content);
          $("#edit-templates-name").val(templatetype_name);
          $("#edit-templates-status").val(templatetype_status);
          resize_dialog(600, 210);
          styleStatusMessages(err_msg, "statusMessage", "failure");
        }
      }
    }
  });
  return false;
}

function activateTemplate(id, status){
  var pageno = $("#hid_pageno").val();
  var msg_str;
  if(status=="Active"){
    status = "Inactive";
    msg_str = 'deactivated';
    var cfrm_msg = 'Deactivate';
  }
  else {
    status = "Active";
    msg_str = 'activated';
    var cfrm_msg = 'Activate';
  }

  openConfirmBox (function () {
		$("#alertdialog").dialog("destroy");
    $('#dialog').html('<div style="padding-top:50px; padding-left:240px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
    $.ajax({
      type : "POST",
      url : baseurl+"templatetype/activate",
      data: "status="+status+"&templateId="+id,
      async : false,
      cache : false,
      success : function (msg) {
        eval("var json="+msg);
        if(json.Message=="Success"){
          $('#dialog').dialog('destroy');
          applyTemplatetypeFilterAction(pageno);
          openAlertDialog(350, 130, 'Information', 'Template type ' + msg_str + ' successfully.', "success");
        }
        if(json.Message=="Error"){
            openAlertDialog(350, 130, 'Information', 'Could not change status.');
        }
      },
      error : function (res) {
        handleRequestError(res);
      }
    });
	}, 300, 130, "Confirm " + cfrm_msg, "Do you want to " + cfrm_msg + " this template type?");
  
  return false;
}


//function to open dialog box for adding new placeholder
function addNewPlaceholderDialog (width, height, title) {
  var wid       = width;
  var heit      = height;
  var buttons   = false;

  $('#dialog').dialog({
    autoOpen    : false,
    width       : wid,
    height      : heit,
    bgiframe    : true,
    resizable   : false,
    title       : title,
    modal       : true,
    show        : 'puff',
    close       : function () {
      $('#dialog').dialog('destroy');
    }
  });
  $('#dialog').dialog('open');
  var h         = heit;
  if(buttons){
    h           = heit-95;
  }else{
    h           = heit-35;
  }
  $('#dialog').css({
    'overflow-y': 'auto',
    'width'     : (wid-18)+'px',
    'height'    : h + 'px'
  }).show();

  $('#dialog').html('<div style="padding-top:50px; padding-left:250px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  addNewPlaceholder();
}

//Function to display Placeholder add form
function addNewPlaceholder() {
  $.ajax({
    type  : "GET",
    url   : baseurl + 'placeholder/add',
    async : true,
    cache : false,
    success : function (res) {
        $('#dialog').html(res);
        $("#edit-placeholder-name").focus();
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
  return false;
}

//Function to save the data for Placeholder
function submitPlaceholder() {
  var placeholder_name      = $.trim($("#edit-placeholder-name").val());
  var placeholder_value     = $.trim($("#edit-placeholder-value").val());
  var placeholder_status    = $.trim($("#edit-placeholder-status").val());
  var message_str           = '';
  var height                = 0;
  var strRegExp             = "^[A-Za-z0-9\\s-_]{1,255}$";

  if (placeholder_name == "") {
      message_str   = message_str + "Please enter the placeholder name <br />";
      height        = height + 20;
  }else if(TestRegExp(placeholder_name, strRegExp) == false){
    message_str = message_str + "Please enter valid placeholder name. Only A-Z a-Z 0-9 - _ and spaces are allowed.<br />";
    height      = height + 20;
  }
  if (placeholder_value == "") {
      message_str   = message_str + "Please enter the placeholder value <br />";
      height        = height + 20;
  }else if(TestRegExp(placeholder_value, strRegExp) == false){
    message_str = message_str + "Please enter valid placeholder value. Only A-Z a-Z 0-9 - _ and spaces are allowed.<br />";
    height      = height + 20;
  }
  if (placeholder_status == "") {
      message_str   = message_str + "Please select status <br />";
      height        = height + 20;
  }

  if(message_str != ""){
    resize_dialog(600, 200 + height);
    styleStatusMessages(message_str, "statusMessage", "failure");
    return false;
  }

  $('#dialog').html('<div style="padding-top:50px; padding-left:250px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type    : "POST",
    url     : baseurl + 'placeholder/add_action',
    data    : '&placeholder_name='+encodeURIComponent(placeholder_name)+ '&placeholder_value='+encodeURIComponent(placeholder_value)+ '&placeholder_status=' + placeholder_status,
    success: function(msg){
      eval("var json="+msg);
      if(json.Message=="Success"){
        $('#dialog').dialog('destroy');
        applyPlaceholderFilterAction(1);
        openAlertDialog(350, 130, 'Information', 'Placeholder created successfully.', "success");
      }else{
          if(json.Message=="Failure"){
            if ((json.Error).search("Custom Placeholder Name Not Unique") >= 0) {
              var err_msg = "Placeholder already exists";
            }
            else {
              var err_msg = json.Error;
            }
            $.ajax({
              type    : "GET",
              url     : baseurl + 'placeholder/add',
              cache   : false,
              success : function (res) {
                $('#dialog').html(res);
                $('#edit-placeholder-name').val(placeholder_name);
                $('#edit-placeholder-value').val(placeholder_value);
                $('#edit-placeholder-status').val(placeholder_status);
                styleStatusMessages(err_msg, "statusMessage", "failure");
              },
              error   : function (res) {
                handleRequestError(res);
              }
            });
            resize_dialog(600, 210+30);
          }
      }
    }
  });
  return false;
}

function openViewPlaceholderDetailDialog(id, width, height, title){
  var wid       = width;
  var heit      = height;
  var buttons   = false;

  $('#dialog').dialog({
    autoOpen    : false,
    width       : wid,
    height      : heit,
    bgiframe    : true,
    resizable   : false,
    title       : title,
    modal       : true,
    show        : 'puff',
    close       : function () {
      $('#dialog').dialog('destroy');
    }
  });
  $('#dialog').dialog('open');
  var h         = heit;
  if(buttons){
    h           = heit-95;
  }else{
    h           = heit-35;
  }
  $('#dialog').css({
    'overflow-y': 'auto',
    'width'     : (wid-18)+'px',
    'height'    : h + 'px'
  }).show();

  $('#dialog').html('<div style="padding-top:50px; padding-left:240px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  viewPlaceholderDetail(id);
}

function viewPlaceholderDetail(id){
  $.ajax({
    type  : "GET",
    url   : baseurl + 'placeholder/detail/' + id,
    async : true,
    cache : false,
    success : function (res) {
        $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
  return false;
}

function activatePlaceholder(id, status){
  var pageno = $("#hid_pageno").val();
  var msg_str   = '';
  if(status=="Active"){
    status  = "Inactive";
    var msg_disp = "deactivated";
    var width = 400;
    msg_str = 'Some of the workflows might be using this placeholder. <br />Do you want to deactivate this placeholder?';
    var cfrm_msg = 'Deactivate';
  }
  else {
    status  = "Active";
    var msg_disp = "activated";
    var width = 350;
    msg_str = 'Do you want to activate this placeholder?';
    var cfrm_msg = 'Activate';
  }

  openConfirmBox (function () {
		$("#alertdialog").dialog("destroy");
    $('#dialog').html('<div style="padding-top:50px; padding-left:250px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
    $.ajax({
      type : "POST",
      url : baseurl+"placeholder/activate",
      data: "status="+status+"&placeholderId="+id,
      async : false,
      cache : false,
      success : function (msg) {
        eval("var json="+msg);
        if(json.Message=="Success"){
          $('#dialog').dialog('destroy');
          applyPlaceholderFilterAction(pageno);
          openAlertDialog(350, 130, 'Information', 'Placeholder ' + msg_disp + ' successfully', "success");
        }
      },
      error : function (res) {
        handleRequestError(res);
      }
    });
	}, width, 130, "Confirm " + cfrm_msg, msg_str);
    
  return false
}

//function to open dialog box for editing placeholder
function editPlaceholderDialog (id, width, height, title) {
  var wid       = width;
  var heit      = height;
  var buttons   = false;

  $('#dialog').dialog({
    autoOpen    : false,
    width       : wid,
    height      : heit,
    bgiframe    : true,
    resizable   : false,
    title       : title,
    modal       : true,
    show        : 'puff',
    close       : function () {
      $('#dialog').dialog('destroy');
    }
  });
  $('#dialog').dialog('open');
  var h         = heit;
  if(buttons){
    h           = heit-95;
  }else{
    h           = heit-35;
  }
  $('#dialog').css({
    'overflow-y': 'auto',
    'width'     : (wid-18)+'px',
    'height'    : h + 'px'
  }).show();

  editPlaceholder(id, title);
}

function editPlaceholder(id, title){
  reopen_dialog(600,210,"Edit " + title);
  $('#dialog').html('<div style="padding-top:50px; padding-left:260px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "GET",
    url : baseurl+'placeholder/edit/'+id,
    async : true,
    cache : false,
    success : function (res) {
        $('#dialog').html(res);
        $("#edit-placeholder-name").focus();
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function editPlaceholderAction(placeholderId) {
  var placeholder_name     = $.trim($("#edit-placeholder-name-hidden").val());
  var placeholder_value    = $.trim($("#edit-placeholder-value").val());
  var placeholder_status   = $.trim($("#edit-placeholder-status").val());
  var message_str          = '';
  var height               = 0;
  var strRegExp         = "^[A-Za-z0-9\\s-_]{1,255}$";

  /*if (placeholder_name == "") {
    message_str = message_str + 'Please enter the placeholder name <br />';
    height      = height + 20;
  }else if(TestRegExp(placeholder_name, strRegExp) == false){
    message_str = message_str + "Please enter valid placeholder name. Only A-Z a-Z 0-9 - _ and spaces are allowed.<br />";
    height      = height + 20;
  }*/
  if (placeholder_value == "") {
    message_str = message_str + 'Please enter the placeholder value <br />';
    height      = height + 20;
  }else if(TestRegExp(placeholder_value, strRegExp) == false){
    message_str = message_str + "Please enter valid placeholder value. Only A-Z a-Z 0-9 - _ and spaces are allowed.<br />";
    height      = height + 20;
  }

  if(message_str != ''){
    resize_dialog(600, 210 + height);
    styleStatusMessages(message_str, "statusMessage", "failure");
    return false;
  }
  var content = $('#dialog').html();
  openConfirmBox(function(){
      $('#dialog').html('<div style="padding-top:50px; padding-left:250px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
      $('#alertdialog').dialog('destroy');
      $.ajax({
        type    : "POST",
        url     : baseurl + 'placeholder/edit_action',
        data    : '&placeholder_id='+encodeURIComponent(placeholderId)+ '&placeholder_name='+encodeURIComponent(placeholder_name)+ '&placeholder_value='+encodeURIComponent(placeholder_value)+ '&placeholder_status=' + placeholder_status,
        success: function(msg){
          eval("var json="+msg);
          if(json.Message=="Success"){
            $('#dialog').dialog('destroy');
            var pageno = parseInt($('#hid_pageno').val());
            applyPlaceholderFilterAction(pageno);
            openAlertDialog(350, 130, 'Information', 'Placeholder updated successfully.', "success");
          }else{
            if(json.Message=="Failure"){
              $('#alertdialog').dialog('destroy');
              $('#dialog').html(content);
              $("#edit-placeholder-name").val(placeholder_name);
              $("#edit-placeholder-value").val(placeholder_value)
              $("#edit-placehoder-status").val(placeholder_status);
              resize_dialog(600, 210+30);
              styleStatusMessages(json.Error, "statusMessage", "failure");
            }
          }
        }
      });
      return false;
  },400,120,"Confirm editing placeholder","Some of the workflows might be using this placeholder and need to <br />publish manually. Do you want to continue editing placeholder?");
  return false;
}


function publishPolicy(policyId) {
  var policy_name       = $.trim($("#edit-policy-name").val());
  var policy_type       = $("#edit-policy-type").val();
  var policy_content    = ckeditor.getData();

  if (policy_name == "") {
    styleStatusMessages("Please enter the policy name", "statusMessage", "failure");
    return false;
  }
  if (policy_content == "") {
    styleStatusMessages("Please enter the policy content", "statusMessage", "failure");
    return false;
  }
  $('#dialog').html('<div style="padding-top:200px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type    : "POST",
    url     : baseurl + 'policy/publish',
    data    : '&policy_id='+encodeURIComponent(policyId)+ '&policy_name='+encodeURIComponent(policy_name) + '&policy_type=' + policy_type + '&policy_content=' + encodeURIComponent(policy_content),
    success: function(msg){
      eval("var json="+msg);
      if(json.Message=="Success"){
        $('#dialog').dialog('destroy');
        openAlertDialog(350, 130, 'Information', 'Policy sent for approval successfully.', "success");
        var pageno = parseInt($('#hid_pageno').val());
        applyPolicyFilterAction(pageno);
      }else{
          if(json.Message=="Failure"){
              $.ajax({
                type : "GET",
                url : baseurl+'policy/edit/'+policyId,
                async : true,
                cache : false,
                success : function (res) {
                    $('#dialog').html(res);
                    $("#edit-policy-name").val(policy_name);
                    $("#edit-policy-type").val(policy_type);
                    $("#edit-policy-content").val(policy_content);
                    fckeditor('edit-policy-content');
                    resize_dialog(700, 510);
                    styleStatusMessages(json.Error, "statusMessage", "failure");
                },
                error : function (res) {
                  handleRequestError(res);
                }
              });
          }else{
              $.ajax({
                type : "GET",
                url : baseurl+'policy/edit/'+policyId,
                async : true,
                cache : false,
                success : function (res) {
                    $('#dialog').html(res);
                    $("#edit-policy-name").val(policy_name);
                    $("#edit-policy-type").val(policy_type);
                    $("#edit-policy-content").val(policy_content);
                    fckeditor('edit-policy-content');
                    resize_dialog(700, 510);
                    if(json.Error == 'null' || typeof(json.Error) == 'undefined'){
                        styleStatusMessages("Policy not published<br />Error Occured: Service was not respondong properly", "statusMessage", "failure");
                    } else {
			styleStatusMessages("Policy not published<br />Error Occured:"+json.Error, "statusMessage", "failure");
                    }
					
                },
                error : function (res) {
                  handleRequestError(res);
                }
              });
          }
      }
    }
  });
  return false;
}

function openViewSitePlaceholderDetailDialog(id, width, height, title){
  var wid       = width;
  var heit      = height;
  var buttons   = false;

  $('#dialog').dialog({
    autoOpen    : false,
    width       : wid,
    height      : heit,
    bgiframe    : true,
    resizable   : false,
    title       : title,
    modal       : true,
    show        : 'puff',
    close       : function () {
      $('#dialog').dialog('destroy');
    }
  });
  $('#dialog').dialog('open');
  var h         = heit;
  if(buttons){
    h           = heit-95;
  }else{
    h           = heit-35;
  }
  $('#dialog').css({
    'overflow-y': 'auto',
    'width'     : (wid-18)+'px',
    'height'    : h + 'px'
  }).show();

  $('#dialog').html('<div style="padding-top:50px; padding-left:240px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  viewSitePlaceholderDetail(id);
}

function viewSitePlaceholderDetail(id){
  $.ajax({
    type  : "GET",
    url   : baseurl + 'placeholdersite/detail/' + id,
    async : true,
    cache : false,
    success : function (res) {
        $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
  return false;
}
//function to open dialog box for editing placeholder
function editSitePlaceholderDialog (id, width, height, title) {
  var wid       = width;
  var heit      = height;
  var buttons   = false;

  $('#dialog').dialog({
    autoOpen    : false,
    width       : wid,
    height      : heit,
    bgiframe    : true,
    resizable   : false,
    title       : title,
    modal       : true,
    show        : 'puff',
    close       : function () {
      $('#dialog').dialog('destroy');
    }
  });
  $('#dialog').dialog('open');
  var h         = heit;
  if(buttons){
    h           = heit-95;
  }else{
    h           = heit-35;
  }
  $('#dialog').css({
    'overflow-y': 'auto',
    'width'     : (wid-18)+'px',
    'height'    : h + 'px'
  }).show();

  editSitePlaceholder(id, title);
}

function editSitePlaceholder(id, title){
  reopen_dialog(550,180,"Override " + title);
  $('#dialog').html('<div style="padding-top:40px; padding-left:240px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "GET",
    url : baseurl+'placeholdersite/override/'+id,
    async : true,
    cache : false,
    success : function (res) {
        $('#dialog').html(res);
        $("#edit-placeholder-value").focus();
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function editSitePlaceholderAction(placeholderId) {
  var placeholder_value    = $.trim($("#edit-placeholder-value").val());
  var message_str          = '';
  var height               = 0;

  if (placeholder_value == "") {
    message_str = message_str + 'Please enter the placeholder value <br />';
    height      = height + 20;
  }

  if(message_str != ''){
    resize_dialog(550, 180 + height);
    styleStatusMessages(message_str, "statusMessage", "failure");
    return false;
  }
  var content = $('#dialog').html();
  openConfirmBox(function(){
      $('#alertdialog').dialog('destroy');
      $('#dialog').html('<div style="padding-top:40px; padding-left:240px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
      $.ajax({
        type    : "POST",
        url     : baseurl + 'placeholdersite/override_action',
        data    : '&placeholder_id='+encodeURIComponent(placeholderId)+ '&placeholder_value='+encodeURIComponent(placeholder_value),
        success: function(msg){
          eval("var json="+msg);
          if(json.Message=="Success"){
            $('#dialog').dialog('destroy');
            $('#alertdialog').dialog('destroy');
            openAlertDialog(350, 130, 'Information', 'Placeholder updated successfully.', "success");
          }else{
              if(json.Message=="Failure"){
                  $('#dialog').html(content);
                  $("#edit-placeholder-value").val(placeholder_value)
                  resize_dialog(550, 180+30);
                  styleStatusMessages(json.Error, "statusMessage", "failure");
              }
          }
        }
      });
      return false;
  },400,120,"Confirm editing placeholder","Some of the workflows might be using this placeholder and need to <br />publish manually. Do you want to continue editing placeholder?");
  return false;
}